/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.utils;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.CacheUtils;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.Servlets;

/**
 * 集团公司工具类
 * @author ThinkGem
 * @version 2015-7-21
 */
public class CorpUtils {

	protected static Logger logger = LoggerFactory.getLogger(CorpUtils.class);
	
	private static final String CORP_CACHE = "corpCache";

	public static final String DEFAULT_CORP_CODE = "0";
	
	/**
	 * 获取当前登录用户的集团公司Code
	 * @return
	 */
	public static String getCurrentCorpCode() {
		String corpCode = "null";
		if (Global.isUseCorpModel()){
			HttpServletRequest request = Servlets.getRequest();
			if (request != null){
				corpCode = (String)request.getAttribute("corpCode__");
				if (StringUtils.isBlank(corpCode)){
					corpCode = UserUtils.getUser().getCorpCode_();
				}
				if (StringUtils.isBlank(corpCode)){
					corpCode = "null";
				}
				request.setAttribute("corpCode__", corpCode);
			}
		}
		return StringUtils.null2blank(corpCode);
	}
	
	/**
	 * 获取当前登录用户的集团公司Name
	 * @return
	 */
	public static String getCurrentCorpName() {
		String corpName = "null";
		if (Global.isUseCorpModel()){
			HttpServletRequest request = Servlets.getRequest();
			if (request != null){
				corpName = (String)request.getAttribute("corpName__");
				if (StringUtils.isBlank(corpName)){
					corpName = UserUtils.getUser().getCorpName_();
				}
				if (StringUtils.isBlank(corpName)){
					corpName = "null";
				}
				request.setAttribute("corpName__", corpName);
			}
		}
		return StringUtils.null2blank(corpName);
	}
	
	/**
	 * 获取缓存值
	 * @param key
	 * @return
	 */
	public static Object getCache(String key) {
		return CacheUtils.get(CORP_CACHE, getCurrentCorpCode() + key);
	}
	
	/**
	 * 获取缓存值
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static Object getCache(String key, Object defaultValue) {
		Object value = getCache(key);
		return value != null ? value : defaultValue;
	}
	
	/**
	 * 设置缓存值
	 * @param key
	 * @param value
	 */
	public static void putCache(String key, Object value) {
		CacheUtils.put(CORP_CACHE, getCurrentCorpCode() + key, value);
	}

	/**
	 * 移除缓存值
	 * @param key
	 */
	public static void removeCache(String key) {
		CacheUtils.remove(CORP_CACHE, getCurrentCorpCode() + key);
	}
	
}
